package task

import (
	"fmt"
	"test/timer/db"
)

// Db 全局变量
var Db = db.Db

// List 任务列表
func List() []Task {
	t := []Task{}
	Db.Select(&t, "select * from jobs order by id desc")
	return t
}

// Add 添加任务
func Add(name, spec, job string, status int) (int, error) {
	rs, err := Db.Exec("insert into jobs(name, spec, job, status) values(?, ?, ?, ?)", name, spec, job, status)
	if err != nil {
		return 0, err
	}
	id, err := rs.LastInsertId()
	return int(id), err
}

// Edit 修改任务
func Edit(id int, spec, job string) error {
	_, err := Db.Exec("update jobs set spec = ?, job = ? where id = ?", spec, job, id)
	return err
}

// SetStatus 更新任务状态
func SetStatus(id, status int) error {
	_, err := Db.Exec("update jobs set status = ? where id = ?", status, id)
	return err
}

// Del 删除任务
func Del(id int) error {
	_, err := Db.Exec("delete from jobs where id = ?", id)
	return err
}

var ts = NewTasks()

// Flush 刷新任务队列
func Flush() {
	ts.Stop()

	l := List()
	for _, v := range l {
		if v.Status == 0 {
			continue
		}
		id := v.ID
		spec := v.Spec
		job := v.Job
		name := v.Name
		fmt.Println(id, name, spec, job)
		//		ts.Add(9, "*/2 * * *", "999")
		ts.Add(id, name, spec, job)
	}

	go ts.Run()
}
